package com.ajie.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 阿里云发送短信服务
 */

@Slf4j
@Component
public class SMSUtils {

    @Value("${aliyun.accessKey}")
    private String accessKey;
    
    @Value("${aliyun.secretKey}")
    private String secretKey;
    
    @Value("${aliyun.signName}")
    private String signName;
    
    @Value("${aliyun.templateCode}")
    private String templateCode;
    
    @Autowired
    private RedisUtil redisUtil;
    
    
    public Client createClient() throws Exception {
        log.info("该文件名是：SMSUtils,该方法是：createClient");
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKey)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(secretKey);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
    
    /**
     * 传入电话号码
     * @param phoneNumbers
     * @return
     */
    public void sendSms(String phoneNumbers,int code){
        log.info("该文件名是：SMSUtils,该方法是：sendSms");
        try {
           
            Client client = this.createClient();
            SendSmsRequest request = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumbers)
                    .setSignName(signName)
                    .setTemplateCode(templateCode)
                    .setTemplateParam("{code: "+code + "}");
            SendSmsResponse response = client.sendSms(request);
            redisUtil.setValueTime("sms",code,5);
            log.error("发送短信验证码成功-->{}",response.getBody().code + "--------------"+ response.getBody().message);
        } catch (Exception e) {
            log.error("发送短信失败-->{}",e.getMessage());
        }
    }
}
